<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>计时器</title>
  </head>
  <body>
    <div id="app">
      <button @click="add">添加</button>
      <button @click="allStop">全部暂停</button>
      <hr />
      <div v-for="(item,index) in list ">
        <button @click="start(item)">开始</button>
        <button @click="stop(item)">暂停</button>
        <button @click="change(item,index)">重置时间间隔</button>
        <button @click="del(item,index)">删除</button>
        <input
          type="text"
          @change="change(item,index)"
          ref="num"
          placeholder="请输入时间间隔"
        />
        <h1>{{item.number}}</h1>
      </div>
    </div>
    <script src="./libs/vue.js"></script>
    <script>
      new Vue({
        el: "#app",
        data: {
          list: [],
        },
        methods: {
          start(item) {
            console.log(item.step);
            // item.time = setInterval(() => {
            //   item.number += Number(item.step);
            // }, 1000);

            // 延时器实现定时器的功能
            let fn = () => {
              item.number += Number(item.step);

              item.time = setTimeout(() => {
                fn();
              }, item.interval);
            };

            item.time = setTimeout(() => {
              fn();
            }, item.interval);
          },
          stop(item) {
            clearInterval(item.time);
          },

          reset(item) {
            clearInterval(item.time);
            item.number = 0;
          },
          change(item, index) {
            item.interval = this.$refs.num[index].value;
          },
          add() {
            this.list.push({
              id: Date.now(),
              number: 0,
              step: 1,
              interval: 1000,
            });
          },
          del(item, index) {
            clearInterval(item.time);
            this.list.splice(index, 1);
          },
          allStop() {
            this.list.map((t) => clearInterval(t.time));
          },
        },
      });
    </script>
  </body>
</html>
